package code.oldCode.binarySearch;

/**
 * @author cuihaoran
 * @date 2024/10/21
 */
public class ListBS {

    /**
     * 704. 二分查找
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (target == nums[mid]) {
                return mid;
            } else if (target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 35. 搜索插入位置
     * @param nums
     * @param target
     * @return
     */
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int ans = nums.length;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            // 当target<=nums[mid]时，将其插入左侧
            if (target <= nums[mid]) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }

    /**
     * 744. 寻找比目标字母大的最小字母
     * @param letters
     * @param target
     * @return
     */
    public char nextGreatestLetter(char[] letters, char target) {
        int left = 0, right = letters.length - 1;
        while(left <= right) {
            int mid = (right - left) / 2 + left;
            if (letters[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return left >= letters.length ? letters[0] : letters[left];
    }

    /**
     * 1351. 统计有序矩阵中的负数
     * @param grid
     * @return
     */
    public int countNegatives(int[][] grid) {
        // grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
        //  4  3  2 -1
        //  4  2  1 -1
        //  1  1 -1 -2
        // -1 -1 -2 -3


        return 0;
    }

    public static void main(String[] args) {

    }
}
